﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SharedLib.WinFormMVCFramework
{
    public class ListBoxItemValueText
    {
        public string Text { get; set; }
        public string Value { get; set; }

        public ListBoxItemValueText(string value, string text)
        {
            if (value == null) throw new ArgumentNullException("value");
            Text = text;
            Value = value;
        }

        public override string ToString()
        {
            return Text;
        }

        public override bool Equals(object obj)
        {
            if (obj is ListBoxItemValueText)
            {
                return Value.Equals(((ListBoxItemValueText)obj).Value);
            }
            else
            {
                return base.Equals(obj);
            }
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }

        
    }

    public static class ComboBoxExtension
    {
        public static bool SelectByValue(this ComboBox listBox, string value)
        {
            if (listBox != null && value != null)
            {
                foreach (object item in listBox.Items)
                {
                    if (item is ListBoxItemValueText)
                    {
                        if (((ListBoxItemValueText)item).Value == value)
                        {
                            listBox.SelectedItem = item;
                            return true;
                        }
                    }
                    else
                    {
                        if (item.ToString() == value)
                        {
                            listBox.SelectedItem = item;
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public static string GetSelectedValue(this ComboBox comboBox)
        {
            if (comboBox == null || comboBox.SelectedItem == null) return null;
            if (comboBox.SelectedItem is ListBoxItemValueText)
            {
                ListBoxItemValueText item = comboBox.SelectedItem as ListBoxItemValueText;
                if (item != null)
                {
                    return item.Value;
                }
                return null;
            }
            else
            {
                return comboBox.SelectedItem.ToString();
            }
        }
    }
}
